package cn.tedu.ivos.dictoption.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.dict.mapper.DictMapper;
import cn.tedu.ivos.dict.pojo.dto.DictQuery;
import cn.tedu.ivos.dict.pojo.vo.DictVO;
import cn.tedu.ivos.dictoption.mapper.DictOptionMapper;
import cn.tedu.ivos.dictoption.pojo.dto.DictOptionAddParam;
import cn.tedu.ivos.dictoption.pojo.dto.DictOptionQuery;
import cn.tedu.ivos.dictoption.pojo.entity.DictOption;
import cn.tedu.ivos.dictoption.pojo.vo.DictOptionVO;
import cn.tedu.ivos.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictOptionServiceImpl implements DictOptionService {
    @Autowired
    private DictOptionMapper dictOptionMapper;
    @Autowired
    private DictMapper dictMapper;
    @Override
    public List<DictOptionVO> selectDictOption(DictOptionQuery query) {
        log.debug("查询字典项业务，参数：{}", query);
        List<DictOptionVO> List= dictOptionMapper.selectDictOption(query);
        return List;
    }

    @Override
    public void saveDictOption(DictOptionAddParam dictOptionAddParam) {
        log.debug("保存字典项业务 dictOptionAddParam{}",  dictOptionAddParam);
        DictOption dictOption = new DictOption();
        BeanUtils.copyProperties(dictOptionAddParam, dictOption);
        if (dictOptionAddParam.getId() == null){
            dictOption.setCreateTime(new Date());
            dictOptionMapper.insertDictOption(dictOption);
        }else {
            dictOption.setUpdateTime(new Date());
            dictOptionMapper.updateDictOption(dictOption);
        }
    }

    @Override
    public void deleteDictOption(Long id) {
        log.debug("删除字典项业务，id:{}", id);
        dictOptionMapper.deleteDictOption(id);
    }

    @Override
    public List<DictOptionVO> selectDictOptionByCode(String code) {
        log.debug("根据字典编码查询字典项业务，code:{}", code);
        DictQuery query = new DictQuery();
        query.setCode(code);
        List<DictVO> list = dictMapper.selectDict(query);
        if (list != null && list.size() > 0){
            DictVO dictVO = list.get(0);
            DictOptionQuery dictOptionQuery = new DictOptionQuery();
            dictOptionQuery.setDictId(dictVO.getId());
            List<DictOptionVO> dictOptionVOList = dictOptionMapper.selectDictOption(dictOptionQuery);
            return dictOptionVOList;
        }else {
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
    }

}
